package com.code.petapp.activity

import android.animation.Animator
import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateInterpolator
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.fragment.app.Fragment
import com.code.petapp.R
import com.code.petapp.databinding.ActivityMainBinding
import com.code.petapp.fragment.FosterFragment
import com.code.petapp.fragment.HallFragment
import com.code.petapp.fragment.HomeFragment
import com.code.petapp.fragment.MyFragment
import com.code.petapp.fragment.ShopFragment
import com.code.petapp.util.SPCommonUtils
import com.code.petapp.util.UiUtils
import com.code.petapp.view.sidemenu.ResourceCable
import com.code.petapp.view.sidemenu.ScreenShotAble
import com.code.petapp.view.sidemenu.SlideMenuItem
import com.code.petapp.view.sidemenu.ViewAnimator


class MainActivity : BaseActivity(), ViewAnimator.ViewAnimatorListener {
    companion object {
        private const val TIME_DIFF = (2 * 1000).toLong()
        const val TAG = "MainActivity"
    }

    private var drawerToggle: ActionBarDrawerToggle? = null
    private lateinit var inflate: ActivityMainBinding
    private val list: ArrayList<SlideMenuItem> = arrayListOf()
    private var viewAnimator: ViewAnimator<*>? = null
    private val fragmentList: ArrayList<Fragment> = arrayListOf()
    private val screenList: ArrayList<ScreenShotAble> = arrayListOf()
    private var currentPosition = -1
    private var mLastBackTime: Long = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        inflate = ActivityMainBinding.inflate(layoutInflater)
        setContentView(inflate.root)
        inflate.drawerLayout.setScrimColor(Color.TRANSPARENT)
        inflate.leftDrawer.setOnClickListener { inflate.drawerLayout.closeDrawers() }
        Log.d(TAG, SPCommonUtils.getInstance().token + " " + SPCommonUtils.getInstance().userId)
        setActionBar()
        createMenuList()//在这里修改或增加需要的fragment
    }

    //添加左侧边栏的Item
    private fun createMenuList() {
        //定义左侧item需要几个就添加几个,第二个参数item显示的图标
        val menuItem = SlideMenuItem(R.drawable.icon_home)
        val menuItem1 = SlideMenuItem(R.drawable.icons_hall)
        val menuItem2 = SlideMenuItem(R.drawable.shopping)
        val menuItem3 = SlideMenuItem(R.drawable.icon_foster)
        val menuItem4 = SlideMenuItem(R.drawable.icons_my)
        list.add(menuItem)
        list.add(menuItem1)
        list.add(menuItem2)
        list.add(menuItem3)
        list.add(menuItem4)
        //创建fragment，需要几个就添加几个
        val pageHome = HomeFragment()
        val pageHall = HallFragment()
        val pageShop = ShopFragment()
        val pageFoster = FosterFragment()
        val pageMy = MyFragment()

        fragmentList.add(pageHome)
        fragmentList.add(pageHall)
        fragmentList.add(pageShop)
        fragmentList.add(pageFoster)
        fragmentList.add(pageMy)

        //初始化页面，传入的参数是进入应用默认显示第几个fragment
        initFragment()
    }

    @SuppressLint("CommitTransaction")
    private fun initFragment() {
        destroyFragment()
        val transaction = supportFragmentManager.beginTransaction()
        for (fragment in fragmentList) {
            if (!fragment.isAdded) {
                transaction.add(R.id.content_frame, fragment)
                transaction.hide(fragment)
            }
        }
        transaction.commitAllowingStateLoss()
        switchFragment(0)
        viewAnimator = ViewAnimator(
            this, list, screenList, inflate.drawerLayout, this
        )
    }

    private fun switchFragment(selectPosition: Int) {
        if (currentPosition == -1 || currentPosition != selectPosition) {
            val beginTransaction = supportFragmentManager.beginTransaction()
            beginTransaction.show(fragmentList[selectPosition])
            if (currentPosition != -1) {
                beginTransaction.hide(fragmentList[currentPosition])
            }
            beginTransaction.commitAllowingStateLoss()
            currentPosition = selectPosition
        }
    }

    private fun setActionBar() {
        setSupportActionBar(inflate.toolbar)
        supportActionBar!!.setHomeButtonEnabled(true)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        drawerToggle = object : ActionBarDrawerToggle(
            this,  /* host Activity */
            inflate.drawerLayout,  /* DrawerLayout object */
            inflate.toolbar,  /* nav drawer icon to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description */
            R.string.drawer_close /* "close drawer" description */
        ) {
            /** Called when a drawer has settled in a completely closed state.  */
            override fun onDrawerClosed(view: View) {
                super.onDrawerClosed(view)
                inflate.leftDrawer.removeAllViews()
                inflate.leftDrawer.invalidate()
            }

            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
                super.onDrawerSlide(drawerView, slideOffset)
                if (slideOffset > 0.6 && inflate.leftDrawer.childCount == 0) viewAnimator!!.showMenuContent()
            }

        }
        inflate.drawerLayout.addDrawerListener(drawerToggle as ActionBarDrawerToggle)
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        drawerToggle!!.syncState()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        drawerToggle!!.onConfigurationChanged(newConfig)
    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        val findItem = menu!!.findItem(R.id.action_settings)
        findItem.setVisible(false)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (drawerToggle!!.onOptionsItemSelected(item)) {
            return true
        }
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onSwitch(
        slideMenuItem: ResourceCable?, selectPosition: Int, topPosition: Int
    ) {
        switchFragment(selectPosition)
        replacePageAnimation(topPosition)
    }

    override fun disableHomeButton() {
        supportActionBar!!.setHomeButtonEnabled(false)
    }

    override fun enableHomeButton() {
        supportActionBar!!.setHomeButtonEnabled(true)
        inflate.drawerLayout.closeDrawers()
    }

    override fun addViewToContainer(view: View?) {
        inflate.leftDrawer.addView(view)
    }

    private fun destroyFragment() {
        val fragmentList = supportFragmentManager.fragments
        for (f in fragmentList) {
            supportFragmentManager.beginTransaction().remove(f).commitAllowingStateLoss()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            val now = System.currentTimeMillis()
            if (now - mLastBackTime < TIME_DIFF) {
                val intent = Intent(Intent.ACTION_MAIN)
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                intent.addCategory(Intent.CATEGORY_HOME)
                startActivity(intent)
                return true
            } else {
                mLastBackTime = now
                Toast.makeText(this, resources.getString(R.string.two_exit), Toast.LENGTH_SHORT)
                    .show()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun replacePageAnimation(topPosition: Int) {
        val bitmap = UiUtils.getScreenShot(inflate.contentFrame)
        val finalRadius: Int = inflate.contentFrame.width.coerceAtLeast(inflate.contentFrame.height)
        val animator: Animator = ViewAnimationUtils.createCircularReveal(
            inflate.contentFrame, 0, topPosition, 0f, finalRadius.toFloat()
        )
        animator.interpolator = AccelerateInterpolator()
        animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION)
        inflate.contentOverlay.background = BitmapDrawable(resources, bitmap)
        animator.start()
    }
}